"""
错误类定义
"""


class Error:
    def __init__(self, pos_start, pos_end, error_name, details) -> None:
        """
        :param pos_start: 错误开始位置
        :param pos_end: 错误结束位置
        :param error_name: 错误类型名称
        :param details: 错误细节
        """
        self.pos_start = pos_start
        self.pos_end = pos_end
        self.error_name = error_name
        self.details = details

    def as_string(self):
        res = f'{self.error_name}: {self.details}'
        res += f'File {self.pos_start.fn}, line {self.pos_end.ln + 1}'
        return res


class IllegalCharError(Error):
    def __init__(self, pos_start, pos_end, details):
        super().__init__(pos_start, pos_end, "非法字符", details)


class InvalidSyntaxError(Error):
    def __init__(self, pos_start, pos_end, details=''):
        super().__init__(pos_start, pos_end, "非法语法", details)


class RunTimeError(Error):
    def __init__(self, pos_start, pos_end, details, context):
        super().__init__(pos_start, pos_end, "运行时错误", details)
        self.context = context

    def as_string(self):
        result = self.generate_traceback()
        result += f'{self.error_name}: {self.details}'
        result += f'文件名: {self.pos_start.fn}, 行号: {self.pos_end.ln + 1}'
        return result

    def generate_traceback(self):
        result = ''
        pos = self.pos_start
        ctxt = self.context
        while ctxt:
            result = f' 文件名 {pos.fn}, 行号 {str(pos.ln + 1)}, 名称 {ctxt.display_name}\n' + result
            pos = ctxt.parent_entry_pos
            ctxt = ctxt.parent

        return '上下文跟踪栈:\n' + result
